package Algorithm;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class SearchByTag implements Search {
    static final String DB_URL = "jdbc:mysql://39.105.0.127:3306/booksite?characterEncoding=utf-8";
    static final String USER = "root";
    static final String PASS = "123456";

    @Override
    public List<String> search(String searchContent) {
        return getSqlResult(searchContent);
    }

    public List<String> getSqlResult(String searchContent){
        List<String> resList = new ArrayList<>();
        Connection connection = null;
        Statement statement = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection(DB_URL, USER, PASS);
            statement = connection.createStatement();
            String sql = "select b.book_id,r.count from doe_book b,book_tag_ref r " +
                    "where r.ref_tag_title = \'"+searchContent+"\' and b.book_id = r.ref_book_id order by r.count desc;";
//            String sql = "select book_id,book_name from doe_book where book_id in(\n" +
//                "select distinct ref_book_id from book_tag_ref where ref_tag_title = \'"+searchContent+"\');";
            System.out.println(sql);
            ResultSet resultSet = statement.executeQuery(sql);
            while (resultSet.next())
            {
                String book_id = resultSet.getString("book_id");
                String count = resultSet.getString("count");
                resList.add(book_id + ":" + count);
            }
            resultSet.close();
            statement.close();
            connection.close();
        }catch (Exception e){
            e.printStackTrace();
        }
        return resList;
    }

}
